package com.group.auth;

import java.io.*;
import java.util.*;

/**
 * @author lenovo
 */
public class AuthManager {
    private static final String USER_FILE = "users.txt";
    private static Map<String, String> userMap = new HashMap<>();

    static {
        loadUsers();
    }

    private static void loadUsers() {
        try (BufferedReader reader = new BufferedReader(new FileReader(USER_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("\t");
                if (parts.length == 2) {userMap.put(parts[0], parts[1]);}
            }
        } catch (IOException e) {
            // ignore file not existing
        }
    }

    public static boolean register(String username, String password) {
        if (userMap.containsKey(username)) {return false;}
        userMap.put(username, password);
        saveUsers();
        return true;
    }

    public static boolean login(String username, String password) {
        return password.equals(userMap.get(username));
    }

    private static void saveUsers() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(USER_FILE))) {
            for (Map.Entry<String, String> e : userMap.entrySet()) {
                writer.write("");
                writer.write(e.getKey() + "\t" + e.getValue() + "\n");
            }
        } catch (IOException e) {
            //
        }
    }
}
